package com.example.toutiao.ui.main.frg

import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.jzvd.Jzvd
import com.example.toutiao.R
import com.example.toutiao.base.BaseFragment
import com.example.toutiao.ui.main.adpater.VideoAdapter
import com.example.toutiao.ui.main.model.MinVideoModel
import com.example.toutiao.ui.main.model.VideoModel
import com.example.toutiao.ui.main.presenter.VideoPresenter
import com.example.toutiao.ui.main.view.VideoView
import kotlinx.android.synthetic.main.fragment_video_list.view.*

class VideoListFragment(id: String) : BaseFragment<VideoView, VideoPresenter>(), VideoView {
    private var views: View? = null
    private var id: String = id
    override fun getLayoutId(): Int = R.layout.fragment_video_list

    override fun initView(view: View) {
        view.rv_video.layoutManager = LinearLayoutManager(activity)
        views = view
        /*监听列表滚动初始化*/
        view.rv_video.addOnChildAttachStateChangeListener(object :
            RecyclerView.OnChildAttachStateChangeListener {
            override fun onChildViewAttachedToWindow(view: View) {

            }
            // 初始化视频
            override fun onChildViewDetachedFromWindow(view: View) {
                val jzvd: Jzvd = view.findViewById(R.id.js_video)
                if (jzvd != null && Jzvd.CURRENT_JZVD != null &&
                    jzvd.jzDataSource.containsTheUrl(
                        Jzvd.CURRENT_JZVD.jzDataSource.currentUrl
                    )
                ){
                    if(Jzvd.CURRENT_JZVD!=null&&Jzvd.CURRENT_JZVD.screen!=Jzvd.SCREEN_FULLSCREEN){
                        Jzvd.releaseAllVideos()
                    }
                }
            }

        })

    }

    override fun initData() {
        getPresenter()!!.getVideo(id)
    }

    override fun createPresenter(): VideoPresenter = VideoPresenter()

    override fun isRegister(): Boolean = false

    override fun <T> setData(data: T) {
        var mList = data as MutableList<VideoModel>
        views!!.rv_video.adapter = VideoAdapter(mList!!)
    }

    override fun setError(err: String) {

    }

    override fun onPause() {
        super.onPause()
        Jzvd.releaseAllVideos()
    }

    override fun onDestroy() {
        super.onDestroy()
        Jzvd.releaseAllVideos()
    }


}